<template>
  <div id="desDiv">
    <!-- 头部 -->
    <div id="headdiv">
      <span>销售订单</span>
    </div>
    <div id="sale">
      <el-button class="add-button" @click="showAddModal"
        >新增销售订单</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-loading"
        class="audit-button"
        @click="handleAudit"
        >审核</el-button
      >

      <el-button
        class="delete-button"
        type="danger"
        icon="el-icon-delete"
        @click="handleDeleteSelected"
        >删除</el-button
      >
    </div>
    <!-- 搜索框 -->
    <div id="search-bar">
      <el-input
        placeholder="请输入表单中的内容进行搜索"
        prefix-icon="el-icon-search"
        v-model="searchKeyword"
        @change="fetchData"
        clearable
      ></el-input>
    </div>

    <div id="searchDate-bar">
      <el-button icon="el-icon-search" circle @change="fetchData"></el-button>
      <!-- 日期选择器 -->
      <el-date-picker
        v-model="searchDate"
        type="date"
        placeholder="选择日期"
        @change="fetchData"
      ></el-date-picker>
    </div>
    <!-- 躯干 -->
    <div id="bodydiv">
      <el-table
        :data="saleOrderData"
        border
        stripe
        class="centered-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="so_code"
          label="销售订单编号"
          width="150px"
        ></el-table-column>
        <el-table-column
          prop="client_head"
          label="客户名称"
          width="120px"
        ></el-table-column>
        <el-table-column
          prop="so_c_property"
          label="客户属性"
          width="auto"
        ></el-table-column>

        <el-table-column prop="so_types" label="产品种类" width="auto">
          <template slot-scope="scope"> {{ scope.row.so_types }} 种 </template>
        </el-table-column>

        <el-table-column prop="so_toNum" label="销售数量" width="auto">
          <template slot-scope="scope">{{ scope.row.so_toNum }}</template>
        </el-table-column>

        <el-table-column
          prop="so_packaging"
          label="打包方式"
          width="auto"
        ></el-table-column>
        <el-table-column prop="so_amount_due" label="应付金额" width="auto">
          <template slot-scope="scope">
            ￥{{ scope.row.so_amount_due }}
          </template>
        </el-table-column>
        <el-table-column prop="so_to_pay" label="订单已付款" width="auto">
          <template slot-scope="scope"> ￥{{ scope.row.so_to_pay }} </template>
        </el-table-column>

        <el-table-column
          prop="so_shipment_status"
          label="发货状态"
          width="auto"
        >
          <template slot-scope="scope">
            {{ scope.row.so_shipment_status == 1 ? "已发货" : "未发货" }}
          </template>
        </el-table-column>

        <el-table-column prop="so_status" label="订单状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color:
                  scope.row.so_status == 0
                    ? 'red'
                    : scope.row.so_status == 1
                    ? 'orange'
                    : '#2ab600',
              }"
            >
              {{
                scope.row.so_status == 0
                  ? "未出库"
                  : scope.row.so_status == 1
                  ? "待出库"
                  : "已出库"
              }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="AuditStatus" label="审核状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.auditStatus == true ? '#2ab600' : 'red',
              }"
            >
              {{ scope.row.auditStatus == true ? "已审核" : "未审核" }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="employee_name"
          label="操作人员"
          width="auto"
        ></el-table-column>
        <el-table-column prop="so_sales_date" label="销售日期" width="auto">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.so_sales_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
              >查看</el-button
            >

            <!-- <el-button
              size="mini"
              type="danger"
              icon="el-icon-back"
              @click="handleReturn(scope.row)"
              >退货</el-button
            > -->
            <el-button
              size="mini"
              :type="
                scope.row.so_Return_status == 1 ||
                scope.row.so_Return_status == 2
                  ? 'danger'
                  : 'primary'
              "
              :icon="scope.row.so_Return_status == 0 ? 'el-icon-back' : ''"
              :disabled="
                scope.row.so_Return_status == 1 ||
                scope.row.so_Return_status == 2
              "
              @click="handleReturn(scope.row)"
            >
              {{
                scope.row.so_Return_status == 0
                  ? "退货"
                  : scope.row.so_Return_status == 1
                  ? "待退货审核"
                  : "已退货"
              }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 下划线分隔 -->
    <el-divider></el-divider>
    <!-- 尾部 -->
    <div id="taildiv">
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="change"
        @current-change="Ymchange"
        :current-page="currentPage"
        :page-sizes="[7, 15, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="rows"
      >
      </el-pagination>
    </div>
    <!-- 添加模态框 -->
    <el-dialog
      :visible.sync="isAddModalVisible"
      class="addmodel"
      width="70%"
      :before-close="handleCloseModal"
    >
      <div class="custom-div1">
        <el-button @click="MainAdd">提交新增</el-button>
      </div>
      <div class="custom-div">
        <span>新增销售订单</span>
      </div>
      <el-button
        class="orange-button"
        style="position: absolute; top: 43px; left: 10; padding: 10px"
        @click="returnToList"
        >返回列表</el-button
      >
      <el-form :model="formCus" class="custom-form" label-position="top">
        <div class="form-items-container">
          <div
            style="
              display: grid;
              grid-template-columns: repeat(4, 1fr);
              gap: 10px;
            "
          >
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户联系人:</label>
              <el-select
                v-model="formCus.client_head"
                auto-complete="off"
                placeholder="请选择客户联系人"
                style="flex: 1; size: large"
                @change="onCustomerContactChange($event)"
                prop="client_head"
              >
                <el-option
                  v-for="contact in contacts"
                  :key="contact.W_code"
                  style="width: 100%"
                  :label="contact.client_head"
                  :value="contact.client_head"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">公司名称:</label>
              <el-input
                v-model="formCus.client_name"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                placeholder="请输入公司名称"
                readonly
              >
              </el-input>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">联系人手机:</label>
              <el-input
                v-model="formCus.client_phone"
                auto-complete="off"
                style="flex: 1"
                placeholder="请输入联系人手机"
                class="kuang"
                readonly
              ></el-input>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户属性:</label>
              <el-select
                v-model="formCus.so_c_property"
                auto-complete="off"
                placeholder="请选择客户属性"
                style="flex: 1"
                prop="so_c_property"
              >
                <el-option
                  v-for="item in list"
                  :key="item.dd_code"
                  :label="item.dd_label"
                  style="width: 100%"
                  :value="item.dd_label"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">打包方式:</label>
              <el-select
                v-model="formCus.so_packaging"
                placeholder="请选择打包方式"
                style="flex: 1"
              >
                <el-option value="散装" label="散装"></el-option>
                <el-option value="包装" label="包装"></el-option>
                <el-option value="散装/包装" label="散装/包装"></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">销售日期:</label>
              <el-date-picker
                v-model="formCus.so_sales_date"
                auto-complete="off"
                type="date"
                placeholder="选择日期"
                style="flex: 1"
                class="kuang"
              ></el-date-picker>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">发货状态:</label>
              <el-select
                v-model="formCus.so_shipment_status"
                placeholder="请选择发货状态"
                style="flex: 1"
              >
                <el-option value="0" label="未发货"></el-option>
                <el-option value="1" label="已发货"></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">优惠金额:</label>
              <el-input
                v-model="formCus.so_preferential"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                @input="updateAmountDue"
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">订单运费:</label>
              <el-input
                v-model="formCus.so_freight"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                @input="updateAmountDue"
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">应付金额:</label>
              <el-input
                v-model="computedAmountDue"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                readonly
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">已支付金额:</label>
              <el-input
                v-model="formCus.so_to_pay"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">销售数量:</label>
              <el-input
                v-model="computedSoToNum"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                readonly
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">操作人员:</label>
              <el-select
                v-model="formCus.employee_name"
                auto-complete="off"
                placeholder="请选择操作人员"
                style="flex: 1; size: large"
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.employee_id"
                  style="width: 100%"
                  :label="employee.employee_name"
                  :value="employee.employee_name"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="button-container">
          <el-button @click="proaddmodel" class="custom-button">添加</el-button>
        </div>

        <!-- 产品列表 -->
        <div class="product-list-container">
          <el-table :data="allData" style="width: 100%" border>
            <el-table-column
              label="序号"
              prop="orders_id"
              type="index"
              width="80"
            ></el-table-column>
            <el-table-column
              label="产品名称"
              prop="orders_product_name"
            ></el-table-column>
            <el-table-column
              label="单位"
              prop="orders_unit"
              width="80"
            ></el-table-column>
            <el-table-column label="单价" prop="orders_unit_price">
              <template slot-scope="scope">
                ￥{{ scope.row.orders_unit_price }}
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="orders_num"></el-table-column>
            <el-table-column label="小计" prop="orders_subtotal">
              <template slot-scope="scope">
                ￥{{ scope.row.orders_subtotal }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template>
                <el-button
                  size="minin"
                  type="danger"
                  icon="el-icon-edit"
                  @click="deleteCustomer(index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage1"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize1"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
          >
          </el-pagination>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="添加"
      :visible.sync="isAddProductVisible"
      width="400px"
      class="qw"
    >
      <el-form label-width="300px">
        <el-form-item
          label="产品名称"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-select
            v-model="form.orders_product_name"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="product in products"
              :key="product.di_id"
              :label="product.di_name"
              :value="product.di_name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="单位"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-select
            v-model="form.orders_unit"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="unit in units"
              :key="unit.dd_code"
              :label="unit.dd_label"
              :value="unit.dd_label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="单价"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="form.orders_unit_price"
            :precision="4"
            :min="1"
            :step="0.1"
            controls-position="right"
            @change="updateSubtotal"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="数量"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="form.orders_num"
            :min="1"
            :step="1"
            controls-position="right"
            @change="updateSubtotal"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="小计"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="form.orders_subtotal"
            :precision="4"
            controls-position="right"
            disabled
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div>
        <span slot="footer" style="display: flex; justify-content: center">
          <el-button
            @click="isAddProductVisible = false"
            style="
              margin-left: 40px;
              background-color: #4fc1b0;
              border-color: #4fc1b0;
              color: #fff;
            "
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="addProduct"
            style="
              margin-left: 20px;
              background-color: #4fc1b0;
              border-color: #4fc1b0;
              color: #fff;
            "
            >确定</el-button
          >
        </span>
      </div>
    </el-dialog>

    <!-- 修改模态框 -->
    <el-dialog
      :visible.sync="isUpdateModalVisible"
      class="addmodel"
      width="70%"
    >
      <div class="custom-div1">
        <el-button @click="MainUpdate">修改</el-button>
      </div>
      <div class="custom-div">
        <span>销售订单详情</span>
      </div>
      <el-button
        class="orange-button"
        style="position: absolute; top: 43px; left: 10; padding: 10px"
        @click="returnToList"
        >返回列表</el-button
      >
      <el-form :model="formCusUpdate" class="custom-form" label-position="top">
        <div class="form-items-container">
          <div
            style="
              display: grid;
              grid-template-columns: repeat(4, 1fr);
              gap: 10px;
            "
          >
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户联系人:</label>
              <el-select
                v-model="formCusUpdate.client_head"
                auto-complete="off"
                placeholder="请选择"
                style="flex: 1; size: large"
                @change="onCustomerContactChange2($event)"
              >
                <el-option
                  v-for="contact in contacts"
                  :key="contact.W_code"
                  style="width: 100%"
                  :label="contact.client_head"
                  :value="contact.client_head"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">公司名称:</label>
              <el-input
                v-model="formCusUpdate.client_name"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                placeholder="请输入公司名称"
                readonly
              >
              </el-input>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">联系人手机:</label>
              <el-input
                v-model="formCusUpdate.client_phone"
                auto-complete="off"
                style="flex: 1"
                placeholder="请输入联系人手机"
                class="kuang"
                readonly
              ></el-input>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户属性:</label>
              <el-select
                v-model="formCusUpdate.so_c_property"
                auto-complete="off"
                placeholder="请选择客户属性"
                style="flex: 1"
              >
                <el-option
                  v-for="item in list"
                  :key="item.dd_code"
                  :label="item.dd_label"
                  style="width: 100%"
                  :value="item.dd_label"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">打包方式:</label>
              <el-select
                v-model="formCusUpdate.so_packaging"
                placeholder="请选择打包方式"
                style="flex: 1"
              >
                <el-option value="散装" label="散装"></el-option>
                <el-option value="包装" label="包装"></el-option>
                <el-option value="散装/包装" label="散装/包装"></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">销售日期:</label>
              <el-date-picker
                v-model="formCusUpdate.so_sales_date"
                auto-complete="off"
                type="date"
                placeholder="选择日期"
                style="flex: 1"
                class="kuang"
              ></el-date-picker>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">发货状态:</label>
              <el-select
                v-model="formCusUpdate.so_shipment_status"
                placeholder="请选择发货状态"
                style="flex: 1"
              >
                <el-option value="0" label="未发货"></el-option>
                <el-option value="1" label="已发货"></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">优惠金额:</label>
              <el-input
                v-model="formCusUpdate.so_preferential"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                @input="updateAmountDue2"
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">订单运费:</label>
              <el-input
                v-model="formCusUpdate.so_freight"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                @input="updateAmountDue2"
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">应付金额:</label>
              <el-input
                v-model="computedAmountDue2"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                readonly
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">已支付金额:</label>
              <el-input
                v-model="formCusUpdate.so_to_pay"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">销售数量:</label>
              <el-input
                v-model="computedSoToNum2"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                readonly
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">操作人员:</label>
              <el-select
                v-model="formCusUpdate.employee_name"
                auto-complete="off"
                placeholder="请选择操作人员"
                style="flex: 1; size: large"
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.employee_id"
                  style="width: 100%"
                  :label="employee.employee_name"
                  :value="employee.employee_name"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="button-container">
          <el-button @click="proUpdatemodel" class="custom-button"
            >添加</el-button
          >
        </div>

        <!-- 产品列表 -->
        <div class="product-list-container">
          <el-table :data="saleOrder_cData" style="width: 100%" border>
            <el-table-column
              label="序号"
              prop="orders_id"
              type="index"
              width="80"
            ></el-table-column>
            <el-table-column
              label="产品名称"
              prop="orders_product_name"
            ></el-table-column>
            <el-table-column
              label="单位"
              prop="orders_unit"
              width="80"
            ></el-table-column>
            <el-table-column label="单价" prop="orders_unit_price">
              <template slot-scope="scope">
                ￥{{ scope.row.orders_unit_price }}
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="orders_num"></el-table-column>
            <el-table-column label="小计" prop="orders_subtotal">
              <template slot-scope="scope">
                ￥{{ scope.row.orders_subtotal }}
              </template>
            </el-table-column>

            <template>
              <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="UpdateXCustomer(scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="DeleteCustomerY(scope.row.orders_id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeModel"
            @current-change="YmchangeModel"
            :current-page="currentPage2"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfroms"
          >
          </el-pagination>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看从添加 -->
    <el-dialog
      title="添加"
      :visible.sync="isUpdateAddProductVisible"
      width="400px"
      class="qw"
    >
      <el-form label-width="300px">
        <el-form-item
          label="产品名称"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-select
            v-model="formAddUpdate.orders_product_name"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="product in productss"
              :key="product.di_id"
              :label="product.di_name"
              :value="product.di_name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="单位"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-select
            v-model="formAddUpdate.orders_unit"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="unit in unitss"
              :key="unit.dd_code"
              :label="unit.dd_label"
              :value="unit.dd_label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="单价"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="formAddUpdate.orders_unit_price"
            :precision="4"
            :min="1"
            :step="0.1"
            controls-position="right"
            @change="updateSubtotal2"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="数量"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="formAddUpdate.orders_num"
            :min="1"
            :step="1"
            controls-position="right"
            @change="updateSubtotal2"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="小计"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="formAddUpdate.orders_subtotal"
            :precision="4"
            controls-position="right"
            disabled
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div>
        <span slot="footer" style="display: flex; justify-content: center">
          <el-button
            @click="isUpdateAddProductVisible = false"
            style="
              margin-left: 40px;
              background-color: #4fc1b0;
              border-color: #4fc1b0;
              color: #fff;
            "
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="AddUpdateProduct"
            style="
              margin-left: 20px;
              background-color: #4fc1b0;
              border-color: #4fc1b0;
              color: #fff;
            "
            >确定</el-button
          >
        </span>
      </div>
    </el-dialog>

    <!-- 查看从修改 -->
    <el-dialog
      title="添加"
      :visible.sync="isaaaUpdateAddProductVisible"
      width="400px"
      class="qw"
    >
      <el-form label-width="300px">
        <el-form-item
          label="序号"
          style="position: relative; margin-left: -180px; top: 10px"
          v-if="Ycchange"
        >
          <el-input
            v-model="formaaaAddUpdate.orders_id"
            controls-position="right"
            v-if="Ycchange"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="产品名称"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-select
            v-model="formaaaAddUpdate.orders_product_name"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="product in productsss"
              :key="product.di_id"
              :label="product.di_name"
              :value="product.di_name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="单位"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-select
            v-model="formaaaAddUpdate.orders_unit"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="unit in unitsss"
              :key="unit.dd_code"
              :label="unit.dd_label"
              :value="unit.dd_label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="单价"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="formaaaAddUpdate.orders_unit_price"
            :precision="4"
            :min="1"
            :step="0.1"
            controls-position="right"
            @change="updateSubtotal3"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="数量"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="formaaaAddUpdate.orders_num"
            :min="1"
            :step="1"
            controls-position="right"
            @change="updateSubtotal3"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="小计"
          style="position: relative; margin-left: -180px; top: 10px"
        >
          <el-input-number
            v-model="formaaaAddUpdate.orders_subtotal"
            :precision="4"
            controls-position="right"
            disabled
          ></el-input-number>
        </el-form-item>

        <el-form-item
          label="外键Id"
          style="position: relative; margin-left: -180px; top: 10px"
          v-if="Ycchange"
        >
          <el-input
            v-model="formaaaAddUpdate.sal_sales_ordersso_id"
            v-if="Ycchange"
          ></el-input>
        </el-form-item>
      </el-form>
      <div>
        <span slot="footer" style="display: flex; justify-content: center">
          <el-button
            @click="isaaaUpdateAddProductVisible = false"
            style="
              margin-left: 40px;
              background-color: #4fc1b0;
              border-color: #4fc1b0;
              color: #fff;
            "
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="aaAddUpdateProduct"
            style="
              margin-left: 20px;
              background-color: #4fc1b0;
              border-color: #4fc1b0;
              color: #fff;
            "
            >确定</el-button
          >
        </span>
      </div>
    </el-dialog>

    <!-- 退货模态框 -->
    <el-dialog title="" :visible.sync="IshandleReturn" width="50%">
      <h3>销售订单基础信息</h3>
      <div class="custom-div2">
        <el-button @click="TuiH">退货</el-button>
      </div>
      <el-form label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货单号">
              <el-input
                v-model="addReturn.return_code"
                placeholder="自动获取系统编号"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号">
              <el-input
                v-model="addReturn.so_code"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期">
              <el-date-picker
                style="width: 200px"
                v-model="addReturn.return_date"
                type="date"
                format="yyyy-MM-dd"
                placeholder="请选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input
                v-model="addReturn.client_head"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input
                v-model="addReturn.client_phone"
                placeholder="请输入"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核人">
              <el-input
                v-model="addReturn.auditor"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间">
              <el-input
                v-model="addReturn.auditTime"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核状态">
              <el-input v-model="displayText" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人员">
              <el-input
                v-model="addReturn.employee_name"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退货原因">
              <el-input
                v-model="addReturn.returmReason"
                placeholder="请输入"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-form-item
            label="外键Id"
            style="position: relative; margin-left: -180px; top: 10px"
            v-if="Ycchange"
          >
            <el-input
              v-model="addReturn.sal_sales_ReturnReturn_Id"
              v-if="Ycchange"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <h3>退货产品明细</h3>

      <div style="overflow-x: auto">
        <el-table
          :data="saleOrder_cData"
          border
          stripe
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column
            prop="return_C_Id"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="orders_product_name"
            label="产品名称"
          ></el-table-column>

          <el-table-column
            prop="orders_unit"
            label="单位"
            width="60"
          ></el-table-column>
          <el-table-column
            prop="orders_num"
            label="销售数量"
            width="80"
          ></el-table-column>

          <el-table-column label="退货入库仓库" width="180">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.w_Name"
                auto-complete="off"
                placeholder="请选择退货仓库"
              >
                <el-option
                  v-for="item in CK"
                  :key="item.w_Name"
                  :label="item.w_Name"
                  :value="item.w_Name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="退货数量">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.return_quantity"
                placeholder="请输入"
                @input="validateReturnQuantity(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.return_remark"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="showDispose(scope.row)" type="text"
                >移除</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeModel"
            @current-change="YmchangeModel"
            :current-page="currentPage2"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfroms"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import { MessageBox } from "element-ui";
import $http from "@/routers/base";
export default {
  data() {
    return {
      form: {
        orders_product_name: "",
        orders_unit: "",
        orders_unit_price: 1,
        orders_num: 1,
        orders_subtotal: 0,
      },
      formAdd: {
        orders_product_name: "",
        orders_unit: "",
        orders_unit_price: 1,
        orders_num: 1,
        orders_subtotal: 0,
      },
      formAddUpdate: {
        orders_product_name: "",
        orders_unit: "",
        orders_unit_price: 1,
        orders_num: 1,
        orders_subtotal: 0,
      },
      formaaaAddUpdate: {
        orders_id: "",
        orders_product_name: "",
        orders_unit: "",
        orders_unit_price: 1,
        orders_num: 1,
        orders_subtotal: 0,
      },
      addReturn: {
        return_Id: "",
        return_code: "",
        so_code: "",
        client_head: "",
        client_phone: "",
        Return_date: "",
        auditor: "",
        auditTime: "",
        AuditStatus: "",
        employee_name: "",
        returmReason: "",

        so_out_status: "", //销售订单/出库状态
      },
      tuihuodata: [], //退货明细
      isUpdateAddProductVisible: false,
      isaaaUpdateAddProductVisible: false,
      products: [], //产品列表下拉数据
      units: [], //单位列表下拉数据
      Ycchange: false,
      productss: [], //产品列表下拉数据
      unitss: [], //单位列表下拉数据
      productsss: [], //产品列表下拉数据
      unitsss: [], //单位列表下拉数据
      CK: [], //仓库下拉
      list: [],
      username: localStorage.getItem("username"),

      formCus: {
        so_id: "",
        so_code: "",
        so_types: "", //产品种类
        so_toNum: "", // 销售数量字段

        client_head: "", // 客户联系人
        client_name: "", // 公司名称
        client_phone: "", // 联系人手机
        so_packaging: "", //打包方式
        so_c_property: "", //客户属性
        so_shipment_status: "", //发货状态
        employee_name: "", //操作人员
        so_preferential: "", //优惠金额
        so_freight: "", //订单运费
        so_amount_due: "", //应付金额
        so_to_pay: "", //已支付金额
        so_sales_date: "", //销售日期

        auditor: "", //审核人
        auditTime: "", //审核时间
        so_Return_status: "", //退货状态
      },
      formCusUpdate: {
        so_id: "",
        so_code: "",
        so_types: "", //产品种类

        so_toNum: "", // 销售数量字段

        client_head: "", // 客户联系人
        client_name: "", // 公司名称
        client_phone: "", // 联系人手机
        so_packaging: "", //打包方式
        so_c_property: "", //客户属性
        so_shipment_status: "", //发货状态
        employee_name: "", //操作人员
        so_preferential: "", //优惠金额
        so_freight: "", //订单运费
        so_amount_due: "", //应付金额
        so_to_pay: "", //已支付金额
        so_sales_date: "", //销售日期
        auditStatus: "",

        auditor: "", //审核人
        auditTime: "", //审核时间
        so_Return_status: "", //退货状态
      },
      contacts: [], // 包含客户联系人、公司名称和联系人电话的数据
      employees: [], //操作人员
      isAddModalVisible: false,
      isAddProductVisible: false,
      currentPage: 1, //当前页
      pageSize: 10, //每页显示数
      rows: 0, //总行数
      searchKeyword: "", //搜索框
      searchDate: "", //日期框
      dateString: "",
      saleOrderData: [], // 销售订单数据
      tableData: [],
      selectedRows: [], // 存储当前选中的行
      testArr: {
        //虚拟数据
      },
      allData: [],
      index: 0,
      currentPage1: 1, //当前页     //虚拟分页
      pageSize1: 3, //每页显示数
      totalItems: 0, //总行数

      selectedModelId: 0,
      sal_sales_ordersso_id: "",

      selectedModelId2: 0,
      sal_sales_ReturnReturn_Id: "",

      currentPage2: 1, //当前页
      pageSize2: 3, //每页显示数
      saleOrder_cData: [], //总行数
      modelfroms: 0,
      where: "",

      isUpdateModalVisible: false,

      subtotalSum: 0, // 用于存储小计总和
      soToNum: 0, //用于存储数量总和

      IshandleReturn: false, //销售退货模态框
    };
  },
  methods: {
    //查询仓库名称
    fetchCK() {
      $http
        .get("InventoryAlerts/IQuery")
        .then((res) => {
          this.CK = res;
        })
        .catch((err) => {
          alert(err);
        });
    },
    //选中行
    handleSelectionChange(selection) {
      this.selectedRows = selection; // 更新选中的行
    },
    //删除
    handleDeleteSelected() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个进行删除");
        return;
      }
      // 检查选中的订单中是否有已经审核通过的（audit_status === true）
      const auditedRows = this.selectedRows.filter(
        (row) => row.auditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的销售订单中已有部分订单已经审核通过，不能删除数据"
        );
        return;
      }

      this.$confirm("此操作将删除选中的销售订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.deleteSaleOrder(row.so_id);
          });
          this.fetchData();
          this.selectedRows = [];
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //删除主表方法
    deleteSaleOrder(so_id) {
      $http
        .delete(`SalesOrder/FromDelete/${so_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error("删除失败，请稍后再试");
          console.error("Delete error:", error);
        });
    },

    //主表添加
    async MainAdd() {
      let so_types = "0"; // 默认值为 '0'，以防止 totalItems 为 undefined 时出错
      if (this.totalItems !== undefined) {
        so_types = this.totalItems.toString();
      }

      let isFormEmpty = true;
      if (
        !this.formCus.client_head &&
        !this.formCus.so_packaging &&
        !this.formCus.so_c_property &&
        !this.formCus.employee_name &&
        !this.formCus.so_sales_date
      ) {
        this.$message.error("数据不能为空，请填写完整表单");
        isFormEmpty = false;
      } else {
        let errorMessage = "";
        if (!this.formCus.client_head) {
          errorMessage = "客户联系人不能为空";
        }
        if (!this.formCus.so_packaging) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "打包方式不能为空";
        }
        if (!this.formCus.so_c_property) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "客户属性不能为空";
        }
        if (!this.formCus.employee_name) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "操作人员不能为空";
        }
        if (!this.formCus.so_sales_date) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "销售日期不能为空";
        }

        if (errorMessage) {
          this.$message.error(errorMessage);
          return;
        }
      }

      if (!isFormEmpty) {
        return;
      }

      const kh = this.formCus.so_c_property.toString();
      this.mainData = {
        so_code: this.formCus.so_code,
        client_head: this.formCus.client_head,
        so_types: so_types,
        so_toNum: this.computedSoToNum,
        client_name: this.formCus.client_name,
        client_phone: this.formCus.client_phone,
        so_packaging: this.formCus.so_packaging,
        so_c_property: kh,
        so_shipment_status: this.formCus.so_shipment_status,
        employee_name: this.formCus.employee_name,
        so_preferential: this.formCus.so_preferential,
        so_freight: this.formCus.so_freight,
        so_amount_due: this.computedAmountDue,
        so_to_pay: this.formCus.so_to_pay,
        so_sales_date: this.formCus.so_sales_date,
        so_status: "0",
        so_created_by: this.username,
        so_created_time: new Date().toISOString(),
        so_update_by: this.username,
        so_update_time: new Date().toISOString(),
        isDeleted: false,
        sal_Orders: this.allData,
        auditStatus: false,

        auditor: null, //审核人
        auditTime: null, //审核时间
        so_Return_status: "0", //退货状态
      };
      $http
        .post("SalesOrder/AddSaleZB", this.mainData)
        .then((response) => {
          if (response) {
            this.$message.success("添加成功！");
            this.fetchData();

            this.isAddModalVisible = false;
            // 清空文本框字段
            this.formCus.client_head = "";
            this.formCus.client_name = "";
            this.formCus.client_phone = "";
            this.formCus.so_packaging;
            this.formCus.so_c_property = "";
            this.formCus.so_shipment_status = "";
            this.formCus.employee_name;
            this.formCus.so_preferential = "";
            this.formCus.so_freight = "";
            this.formCus.so_to_pay;
            this.formCus.so_sales_date = "";
            this.computedAmountDue = "";
            this.computedSoToNum = "";

            this.allData = [];
            this.testArr = [];
            this.totalItems = 0;
          } else {
            this.$message.error("添加失败！请重新添加！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },

    //从表添加
    addProduct() {
      if (this.testArr.length > 0) {
        this.allData = this.testArr;
      }
      // 将表单数据添加到暂时保存数据的数组中
      this.allData.push({
        orders_product_name: this.form.orders_product_name,
        orders_unit: this.form.orders_unit,
        index: this.allData.length, // 保存当前数据项的下标
        orders_unit_price: this.form.orders_unit_price,
        orders_num: this.form.orders_num,
        orders_subtotal: this.form.orders_subtotal,
      }),
        // 清空表单数据
        (this.form.orders_product_name = "");
      this.form.orders_unit = "";
      this.form.orders_unit_price = 1;
      this.form.orders_num = 1;
      this.form.orders_subtotal = 0;

      // 将 allData 的值深拷贝给 testArr
      this.testArr = JSON.parse(JSON.stringify(this.allData));
      // 更新总条目数
      this.totalItems = this.allData.length;
      // 提示用户添加成功
      this.$message.success("添加成功！");
      this.isAddProductVisible = false; // 关闭对话框
      this.currentPage1 = 1;
      this.End();
      // 输出数组的最后一个元素的索引
      console.log(JSON.stringify("123" + this.allData));
    },
    handleCloseModal(done) {
      this.allData = [];
      this.testArr = [];
      this.totalItems = 0;
      done();
    },
    //日期转型
    formatDate(dateString) {
      if (!dateString) {
        return "";
      }
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return "";
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    //分页查询主表
    fetchData() {
      this.dateString = moment(this.searchDate).format("YYYY-MM-DD");
      this.where = "1=1 ";
      if (this.searchDate) {
        this.where += `and (CAST(so_sales_date AS DATE) ='${this.dateString}')`;
      }
      if (this.searchKeyword) {
        this.where += `and (client_head like '%${this.searchKeyword}%' or client_name like '%${this.searchKeyword}%' or employee_name like '%${this.searchKeyword}%' or so_code like '%${this.searchKeyword}%')`;
      }
      $http
        .get("SalesOrder/getFenYe", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleOrderData = res.saleOrderData;
          this.rows = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    change: function (size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchData();
    },
    Ymchange: function (page) {
      this.currentPage = page;
      this.fetchData();
    },
    //返回列表
    returnToList() {
      this.isAddModalVisible = false;
      this.formCus.client_head = "";
      this.formCus.client_name = "";
      this.formCus.client_phone = "";
      this.formCus.so_packaging = "";
      this.formCus.so_c_property = "";
      this.formCus.so_shipment_status = "";
      this.formCus.employee_name = "";
      this.formCus.so_preferential = "";
      this.formCus.so_freight = "";
      this.formCus.so_amount_due = "";
      this.formCus.so_to_pay = "";
      this.formCus.so_sales_date = "";

      this.allData = [];
      this.testArr = [];
      this.totalItems = 0;
    },
    //销售订单模态框
    showAddModal() {
      this.isAddModalVisible = true;
    },
    //添加产品模态框
    proaddmodel() {
      this.isAddProductVisible = true;
      this.fetchUnits();
      this.fetchProducts();
    },
    // 计算小计
    updateSubtotal() {
      this.form.orders_subtotal = (
        this.form.orders_unit_price * this.form.orders_num
      ).toFixed(4);
    },
    updateSubtotal2() {
      this.formAddUpdate.orders_subtotal = (
        this.formAddUpdate.orders_unit_price * this.formAddUpdate.orders_num
      ).toFixed(4);
    },
    updateSubtotal3() {
      this.formaaaAddUpdate.orders_subtotal = (
        this.formaaaAddUpdate.orders_unit_price *
        this.formaaaAddUpdate.orders_num
      ).toFixed(4);
    },
    updateAmountDue() {
      // 当运费或优惠金额发生变化时，手动触发计算属性的更新
      this.$nextTick(() => {
        this.computedAmountDue;
      });
      this.formCus.so_to_pay = this.computedAmountDue;
    },
    updateAmountDue2() {
      // 当运费或优惠金额发生变化时，手动触发计算属性的更新
      this.$nextTick(() => {
        this.computedAmountDue2;
      });
      this.formCusUpdate.so_to_pay = this.computedAmountDue2;
    },
    // 当客户联系人选择变化时触发
    onCustomerContactChange(selectedContact) {
      const contactInfo = this.contacts.find(
        (c) => c.client_head === selectedContact
      );
      if (contactInfo) {
        this.formCus.client_name = contactInfo.client_name;
        this.formCus.client_phone = contactInfo.client_phone;
      }
    },
    //修改客户触发
    onCustomerContactChange2(selectedContact) {
      const contactInfo = this.contacts.find(
        (c) => c.client_head === selectedContact
      );
      if (contactInfo) {
        this.formCusUpdate.client_name = contactInfo.client_name;
        this.formCusUpdate.client_phone = contactInfo.client_phone;
      }
    },
    // 加载客户联系人数据
    loadContacts() {
      $http
        .get("bs_client/Index")
        .then((response) => {
          if (response) {
            this.contacts = response;
          } else {
            console.error("Invalid response format:", response);
          }
        })
        .catch((error) => {
          console.error("Error fetching contacts:", error);
        });
    },
    // 加载操作人员数据
    loadEmployee() {
      $http
        .get("Employee/Query")
        .then((response) => {
          if (response) {
            this.employees = response;
          } else {
            console.error("Invalid response format:", response);
          }
        })
        .catch((error) => {
          console.error("Error fetching contacts:", error);
        });
    },
    //单位下拉
    fetchUnits() {
      $http
        .get("dict_data/Queryunit")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.units = response;
          this.units.forEach((unit) => {
            console.log(unit.dd_label);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    fetchUnits2() {
      $http
        .get("dict_data/Queryunit")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.unitss = response;
          this.unitss.forEach((unit) => {
            console.log(unit.dd_label);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    fetchUnits3() {
      $http
        .get("dict_data/Queryunit")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.unitsss = response;
          this.unitsss.forEach((unit) => {
            console.log(unit.dd_label);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    //客户属性下拉
    fetchCUs() {
      $http
        .get("dict_data/Queryclient")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.list = response;
          this.list.forEach((item) => {
            console.log(item.dd_label);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    //产品名称下拉
    fetchProducts() {
      $http
        .get("dict_image/Queryproducts")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.products = response;
          this.products.forEach((product) => {
            console.log(product.di_name);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    fetchProducts2() {
      $http
        .get("dict_image/Queryproducts")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.productss = response;
          this.productss.forEach((product) => {
            console.log(product.di_name);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    fetchProducts3() {
      $http
        .get("dict_image/Queryproducts")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.productsss = response;
          this.productsss.forEach((product) => {
            console.log(product.di_name);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    //虚拟删除
    deleteCustomer(index) {
      // 首先确保下标在合法范围内
      if (index >= 0 && index < this.allData.length) {
        // 从数组中删除指定下标的元素
        this.allData.splice(index, 1);
        // 更新总条目数
        this.totalItems = this.allData.length;
        // 深拷贝 allData 的值给 testArr
        this.testArr = JSON.parse(JSON.stringify(this.allData));
        // 提示用户删除成功
        this.$message.success("删除成功！");
      } else {
        // 如果下标不在合法范围内，给出相应的提示
        this.$message.error("无法删除，下标越界！");
      }
    },
    //修改模态框
    handleSee(row) {
      this.isUpdateModalVisible = true;
      this.selectedModelId = row.so_id;
      this.formCusUpdate.sal_sales_ordersso_id = this.selectedModelId;
      this.fetchData();
      this.fetchUpaheModeFrom();
      this.$set(this.formCusUpdate, "so_id", row.so_id);
      this.$set(this.formCusUpdate, "so_code", row.so_code);
      this.$set(this.formCusUpdate, "client_head", row.client_head);
      this.$set(this.formCusUpdate, "client_name", row.client_name);
      this.$set(this.formCusUpdate, "client_phone", row.client_phone);
      this.$set(this.formCusUpdate, "so_packaging", row.so_packaging);
      this.$set(this.formCusUpdate, "so_c_property", row.so_c_property);
      this.$set(
        this.formCusUpdate,
        "so_shipment_status",
        row.so_shipment_status
      );
      this.$set(this.formCusUpdate, "so_status", row.so_status);
      this.$set(this.formCusUpdate, "employee_name", row.employee_name);
      this.$set(this.formCusUpdate, "so_preferential", row.so_preferential);
      this.$set(this.formCusUpdate, "so_freight", row.so_freight);
      this.$set(this.formCusUpdate, "so_amount_due", row.so_amount_due);
      this.$set(this.formCusUpdate, "so_to_pay", row.so_to_pay);
      this.$set(this.formCusUpdate, "so_toNum", row.so_toNum);
      this.$set(this.formCusUpdate, "so_sales_date", row.so_sales_date);
      this.$set(this.formCusUpdate, "auditStatus", row.auditStatus);

      this.$set(this.formCusUpdate, "auditor", row.auditor);
      this.$set(this.formCusUpdate, "auditTime", row.auditTime);
      this.$set(this.formCusUpdate, " so_Return_status", row.so_Return_status);
    },
    //修改分页
    fetchUpaheModeFrom() {
      this.where = "sal_sales_ordersso_id=" + this.selectedModelId;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("SalesOrder/ModelFromFenYe", {
          params: {
            currentPage: this.currentPage2,
            pageSize: this.pageSize2,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleOrder_cData = res.saleOrder_cData;
          this.modelfroms = res.rows;

          // 计算小计总和
          let subtotalSum = 0;
          this.saleOrder_cData.forEach((item) => {
            subtotalSum += parseFloat(item.orders_subtotal);
          });
          this.subtotalSum = subtotalSum; // 将小计总和保存到组件变量中

          //计算数量总和
          let soToNum = 0;
          this.saleOrder_cData.forEach((item) => {
            soToNum += parseInt(item.orders_num);
          });
          this.soToNum = soToNum;

          console.log("小计总和：", this.subtotalSum);
          console.log("数量总和：", this.soToNum);
        })
        .catch((error) => {
          //console.error("Error fetching client data: ", error);
        });
    },
    fetchUpaheModeFrom2() {
      this.where = "sal_sales_ordersso_id=" + this.selectedModelId2;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("SalesOrder/ModelFromFenYe", {
          params: {
            currentPage: this.currentPage2,
            pageSize: this.pageSize2,
            where: this.where,
          },
        })
        .then((res) => {
          this.saleOrder_cData = res.saleOrder_cData;
          this.modelfroms = res.rows;
          // 计算小计总和
          let subtotalSum = 0;
          this.saleOrder_cData.forEach((item) => {
            subtotalSum += parseFloat(item.orders_subtotal);
          });
          this.subtotalSum = subtotalSum; // 将小计总和保存到组件变量中

          //计算数量总和
          let soToNum = 0;
          this.saleOrder_cData.forEach((item) => {
            soToNum += parseInt(item.orders_num);
          });
          this.soToNum = soToNum;

          console.log("小计总和：", this.subtotalSum);
          console.log("数量总和：", this.soToNum);
        })
        .catch((error) => {
          //console.error("Error fetching client data: ", error);
        });
    },
    changeModel: function (size) {
      this.pageSize2 = size;
      this.currentPage2 = 1;
      this.fetchUpaheModeFrom(); // 切换每页显示数后重新获取数据
      this.fetchUpaheModeFrom2();
    },
    YmchangeModel: function (page) {
      this.currentPage2 = page;
      this.fetchUpaheModeFrom(); // 重新获取数据
      this.fetchUpaheModeFrom2();
    },
    //虚拟分页
    handleSizeChange: function (size) {
      this.pageSize1 = size;
      this.currentPage1 = 1;
      this.End();
    },
    handleCurrentChange: function (page) {
      this.currentPage1 = page;
      this.End();
    },
    End() {
      // 根据当前页数和每页显示的条目数，截取相应的数据
      const startIndex = (this.currentPage1 - 1) * this.pageSize1;
      const endIndex = startIndex + this.pageSize1;
      this.allData = this.testArr.slice(startIndex, endIndex);
    },
    //查看修改
    MainUpdate() {
      let so_types = "0"; // 默认值为 '0'，以防止 totalItems 为 undefined 时出错
      if (this.modelfroms !== undefined) {
        so_types = this.modelfroms.toString();
      }
      // 检查审核状态，如果为 true，则不允许修改
      if (this.formCusUpdate.auditStatus === true) {
        this.$message.error("修改失败：该订单已被审核，不能进行修改！");
        return;
      }
      if (
        this.formCusUpdate.so_Return_status == "1" ||
        this.formCusUpdate.so_Return_status == "2"
      ) {
        this.$message.error("修改失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      $http
        .put("SalesOrder/UpdateClient", {
          so_id: this.formCusUpdate.so_id,
          so_code: this.formCusUpdate.so_code,
          client_head: this.formCusUpdate.client_head,
          so_types: so_types,

          so_toNum: this.computedSoToNum2,

          client_name: this.formCusUpdate.client_name,
          client_phone: this.formCusUpdate.client_phone,
          so_packaging: this.formCusUpdate.so_packaging,
          so_c_property: this.formCusUpdate.so_c_property,
          so_shipment_status: this.formCusUpdate.so_shipment_status,
          employee_name: this.formCusUpdate.employee_name,
          so_preferential: this.formCusUpdate.so_preferential,
          so_freight: this.formCusUpdate.so_freight,
          so_amount_due: this.computedAmountDue2,
          so_to_pay: this.formCusUpdate.so_to_pay,
          so_sales_date: this.formCusUpdate.so_sales_date,
          so_status: this.formCusUpdate.so_status,
          so_Return_status: this.formCusUpdate.so_Return_status,
          so_created_by: this.username,
          so_created_time: new Date(),
          so_update_by: this.username,
          so_update_time: new Date(),
          isDeleted: false,
          sal_Orders: [
            {
              orders_product_name: "",
              orders_unit: "",
              orders_unit_price: 1,
              orders_num: 1,
              orders_subtotal: 0,
            },
          ],
        })
        .then((response) => {
          if (response) {
            this.$message.success("修改成功！");
            this.fetchData();

            this.isUpdateModalVisible = false;
          } else {
            console.log("修改的值：" + this.response);
            this.$message.error("修改失败！请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
    },
    //查看添加
    proUpdatemodel() {
      this.isUpdateAddProductVisible = true;
      this.fetchUnits2();
      this.fetchProducts2();
    },
    //查看修改添加
    AddUpdateProduct() {
      // 检查审核状态，如果为 true，则不允许修改
      if (this.formCusUpdate.auditStatus === true) {
        this.$message.error("修改失败：该订单已被审核，不能进行修改！");
        return;
      }
      $http
        .post("SalesOrder/AddSaleCB", {
          orders_id: this.formAddUpdate.orders_id,
          sal_sales_ordersso_id: "" + this.selectedModelId,
          orders_product_name: this.formAddUpdate.orders_product_name,
          orders_unit: this.formAddUpdate.orders_unit,
          orders_unit_price: this.formAddUpdate.orders_unit_price,
          orders_num: this.formAddUpdate.orders_num,
          orders_subtotal: this.formAddUpdate.orders_subtotal,
          IsDeleted: false,
        })
        .then((response) => {
          if (response) {
            this.$message.success("添加成功！");
            this.fetchUpaheModeFrom();

            this.isUpdateAddProductVisible = false;

            this.formAddUpdate.orders_product_name = "";
            this.formAddUpdate.orders_unit = "";
            this.formAddUpdate.orders_unit_price = "";
            this.formAddUpdate.orders_subtotal = "";
            this.formAddUpdate.orders_num = "";
          } else {
            this.$message.error("添加失败！请重新添加！");
            console.log("laoliu" + response);
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },
    //查看删除
    async DeleteCustomerY(orders_id) {
      MessageBox.confirm("确认删除删除该条记录吗？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "bs_model",
      })
        .then(() => {
          $http
            .delete(`SalesOrder/FromDeleteModel/${orders_id}`)
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.fetchUpaheModeFrom();
            })
            .catch((error) => {
              this.$message.error("删除失败：" + error.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "管理员取消了删除,删除无效哦！",
          });
        });
    },
    //查看从修改填值
    UpdateXCustomer(row) {
      this.isaaaUpdateAddProductVisible = true;
      this.fetchUnits3();
      this.fetchProducts3();
      this.$set(this.formaaaAddUpdate, "orders_id", row.orders_id);
      this.$set(
        this.formaaaAddUpdate,
        "orders_product_name",
        row.orders_product_name
      );
      this.$set(this.formaaaAddUpdate, "orders_unit", row.orders_unit);
      this.$set(
        this.formaaaAddUpdate,
        "orders_unit_price",
        row.orders_unit_price
      );
      this.$set(this.formaaaAddUpdate, "orders_num", row.orders_num);
      this.$set(this.formaaaAddUpdate, "orders_subtotal", row.orders_subtotal);
      this.$set(
        this.formaaaAddUpdate,
        "sal_sales_ordersso_id",
        row.sal_sales_ordersso_id
      );
    },
    //查看从修改
    aaAddUpdateProduct() {
      $http
        .put("SalesOrder/FormUpdateClient", {
          orders_id: this.formaaaAddUpdate.orders_id,
          orders_product_name: this.formaaaAddUpdate.orders_product_name,
          orders_unit: this.formaaaAddUpdate.orders_unit,
          orders_unit_price: this.formaaaAddUpdate.orders_unit_price,
          orders_num: this.formaaaAddUpdate.orders_num,
          orders_subtotal: this.formaaaAddUpdate.orders_subtotal,
          sal_sales_ordersso_id: this.formaaaAddUpdate.sal_sales_ordersso_id,
        })
        .then((response) => {
          if (response) {
            this.$message.success("修改成功！");
            this.fetchUpaheModeFrom();

            this.isaaaUpdateAddProductVisible = false;
          } else {
            this.$message.error("修改失败！ 请重新修改！");
          }
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
    },
    //审核
    handleAudit() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个销售订单进行审核");
        return;
      }

      // 检查选中的订单中是否有已经审核通过的（audit_status === true）
      const auditedRows = this.selectedRows.filter(
        (row) => row.auditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的销售订单中已有部分订单已经审核通过，不能再次审核"
        );
        return;
      }

      this.$confirm("此操作将审核选中的销售订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.auditSaleOrder(row.so_id);
          });
          this.selectedRows = [];
          this.fetchData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消审核",
          });
        });
    },
    //审核方法
    auditSaleOrder(so_id) {
      $http
        .post(`SalesOrder/AuditSalesOrder/${so_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error("审核失败，请稍后再试");
          console.error("Audit error:", error);
        });
    },
    //退货
    handleReturn(row) {
      this.IshandleReturn = true;
      this.selectedModelId2 = row.so_id;
      this.formCusUpdate.sal_sales_ordersso_id = this.selectedModelId2;
      this.fetchData();
      this.fetchUpaheModeFrom2();
      this.$set(this.addReturn, "return_Id", row.return_Id);
      this.$set(this.addReturn, "so_code", row.so_code);
      this.$set(this.addReturn, "client_head", row.client_head);
      this.$set(this.addReturn, "client_phone", row.client_phone);
      this.$set(this.addReturn, "employee_name", row.employee_name);
      this.$set(this.addReturn, "auditStatus", row.auditStatus);
      this.$set(this.addReturn, "auditor", row.auditor);
      this.$set(this.addReturn, "auditTime", row.auditTime);
      this.$set(this.addReturn, "return_status", row.so_Return_status);
      this.$set(this.addReturn, "so_out_status", row.so_status);
      console.log(JSON.stringify(row, null, 2));
    },
    TuiH() {
      let isFormEmpty = true;
      if (!this.addReturn.returmReason && !this.addReturn.return_date) {
        this.$message.error("数据不能为空，请填写完整表单");
        isFormEmpty = false;
      } else {
        let errorMessage = "";
        if (!this.addReturn.returmReason) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "退货原因不能为空";
        }
        if (!this.addReturn.return_date) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "退货日期不能为空";
        }

        if (errorMessage) {
          this.$message.error(errorMessage);
          return;
        }
      }
      if (!isFormEmpty) {
        return;
      }

      if (this.saleOrder_cData && this.saleOrder_cData.length > 0) {
        for (let item of this.saleOrder_cData) {
          for (let key in item) {
            if (
              item[key] === undefined ||
              item[key] === null ||
              item[key] === ""
            ) {
              this.$message.error("退货产品信息不完整，请填写所有必填项");
              return;
            }
          }
        }
      } else {
        this.$message.error("退货产品列表不能为空");
        return;
      }

      this.mainData = {
        return_code: this.addReturn.return_code,
        so_code: this.addReturn.so_code,
        client_head: this.addReturn.client_head,
        client_phone: this.addReturn.client_phone,

        so_out_status: this.addReturn.so_out_status,
        return_status: "1",

        return_date: this.addReturn.return_date,
        isDeleted: false,
        auditor: this.addReturn.auditor,
        auditTime: this.addReturn.auditTime,
        auditStatus: this.addReturn.auditStatus,
        employee_name: this.addReturn.employee_name,
        returmReason: this.addReturn.returmReason,
        sal_sales_Return_C: this.saleOrder_cData,
      };
      $http
        .post("SalesReturn/AddReturn", this.mainData)
        .then((response) => {
          if (response) {
            this.$message.success("退货成功！");
            this.$router.push("/sale_SaleReturn");
            this.fetchData();
            this.IshandleReturn = false;
          } else {
            this.$message.error("退货失败！请重新操作！");
          }
        })
        .catch((error) => {
          this.$message.error("退货失败：" + error.message);
        });
    },
    // 验证退货数量是否大于销售数量
    validateReturnQuantity(row) {
      if (row.return_quantity > row.orders_num) {
        this.$message.error("退货数量不能大于销售数量");
        // 如果退货数量大于销售数量，则重置为销售数量
        row.return_quantity = row.orders_num;
      }
    },
  },
  mounted() {
    this.fetchUpaheModeFrom();
    this.fetchUpaheModeFrom2();
    this.loadContacts();
    this.fetchCUs();
    this.loadEmployee();
    this.fetchData();
    this.fetchCK();
  },
  computed: {
    // 计算应付金额
    computedAmountDue() {
      let subtotal = 0;
      this.allData.forEach((item) => {
        // 假设orders_subtotal是存储小计的属性名
        subtotal += parseFloat(item.orders_subtotal); // 累加所有小计
      });
      // 假设formCus是另一个对象，包含so_freight和so_preferential属性
      return (
        parseFloat(subtotal) +
        parseFloat(this.formCus.so_freight) -
        parseFloat(this.formCus.so_preferential)
      );
    },
    computedAmountDue2() {
      // 计算小计、订单运费和优惠金额的总和
      return (
        parseFloat(this.subtotalSum) + // 小计总和
        parseFloat(this.formCusUpdate.so_freight) - // 订单运费
        parseFloat(this.formCusUpdate.so_preferential) // 优惠金额
      );
    },
    //计算数量
    computedSoToNum() {
      return parseInt(this.soToNum);
    },
    computedSoToNum2() {
      return parseInt(this.soToNum);
    },
    displayText() {
      return this.addReturn.auditStatus ? "已审核" : "未审核";
    },
  },
};
</script>
<style scoped src="../CSS/SaleOrder.css"></style>
<style scoped>
.form-items-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20px;
  /* 两边留出20px的空隙 */
}

/* 设置文本框的样式 */
.el-form-item__content {
  flex-grow: 1;
}

.form-item {
  flex: 0 0 calc(25% - 40px);
  /* 减去两侧各20px的空隙 */
  max-width: 250px;
  /* 设置文本框的最大宽度 */
  margin: 10px 0;
  /* 上下留出10px的空隙 */
}

.el-form-item__label {
  width: 120px;
  /* 可以调整标签的宽度 */
  text-align: right;
  padding-right: 10px;
}

.el-input__inner,
.el-select .el-input {
  max-width: 200px;
  /* 可以调整输入框的最大宽度 */
}

@media (max-width: 800px) {
  .form-item {
    flex-basis: 100%;
    margin: 10px 0;
  }
}

.button-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* 垂直居中 */
  height: 100%;
  /* 确保按钮容器占据整个高度 */
  padding-top: 10px;
  float: left;
}

.custom-button {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  background-color: #1abc9c;
  width: 60px;
  height: 30px;
  color: #fff;
  font-size: 12px;
  border: none;
}

.custom-form {
  margin: 20px;
}

.kuang {
  width: 60px;
  font-size: small;
}

.orange-button {
  font-size: small;
}

.addmodel {
  left: 120px;
}

.caoz {
  width: 70px;
  font-size: small;
}
</style>
